﻿using FastORM.Entity;
using FastORM.Mapping;
using FastUtil.Convert;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace FastCloud.Base.Desgin
{
    public class CloudModelBinder : IModelBinder
    {
        private readonly Type _type;

        public CloudModelBinder(Type type)
        {
            _type = type;
        }

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            IFormCollection FormParam = bindingContext.HttpContext.Request.Form;
            JArray UpdateFieldList = new JArray();
            JObject Param = new JObject();
            foreach (var item in FormParam)
            {
                UpdateFieldList.Add(item.Key);
                Param.Add(item.Key, ValueConvert.ConvertToString(item.Value));
            }
            Param.Add("UpdateFieldList", UpdateFieldList);
            bindingContext.Result = ModelBindingResult.Success(JsonConvert.DeserializeObject(Param.ToString(), _type));
            return Task.CompletedTask;
        }

    }
}
